<template>
  <view class="pending-sign-detail">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <image src="/static/icons/arrow-left.svg" class="icon-image" mode="aspectFit"></image>
        </view>
        <view class="navbar-title">{{ parkingLotName }}待签人员</view>
        <view class="navbar-right"></view>
      </view>
    </view>

    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 统计概览 -->
      <view class="stats-overview">
        <view class="stats-card">
          <view class="stats-number">{{ personnelList.length }}</view>
          <view class="stats-label">待签人数</view>
        </view>
        <view class="stats-card">
          <view class="stats-number">{{ getOverdueCount() }}</view>
          <view class="stats-label">超时人数</view>
        </view>
        <view class="stats-card">
          <view class="stats-number">{{ getTodayCount() }}</view>
          <view class="stats-label">今日应签</view>
        </view>
      </view>

      <!-- 筛选器 -->
      <view class="filter-section">
        <view class="filter-tabs">
          <view 
            class="filter-tab" 
            :class="{ active: activeFilter === 'all' }"
            @click="setFilter('all')"
          >
            全部
          </view>
          <view 
            class="filter-tab" 
            :class="{ active: activeFilter === 'overdue' }"
            @click="setFilter('overdue')"
          >
            超时
          </view>
          <view 
            class="filter-tab" 
            :class="{ active: activeFilter === 'today' }"
            @click="setFilter('today')"
          >
            今日应签
          </view>
        </view>
      </view>

      <!-- 人员列表 -->
      <view class="personnel-list">
        <view 
          v-for="person in filteredPersonnelList" 
          :key="person.id" 
          class="personnel-item"
          @click="viewPersonDetail(person)"
        >
          <view class="item-header">
            <view class="person-avatar">
              <text class="avatar-text">{{ person.name.charAt(0) }}</text>
            </view>
            <view class="person-info">
              <view class="person-name">{{ person.name }}</view>
              <view class="person-position">{{ person.position }}</view>
            </view>
            <view class="person-status" :class="getStatusClass(person)">{{ getStatusText(person) }}</view>
          </view>
          
          <view class="item-content">
            <view class="info-row">
              <image src="/static/icons/phone.svg" class="icon-image-small" mode="aspectFit"></image>
              <text class="info-text">{{ person.phone }}</text>
            </view>
            <view class="info-row">
              <image src="/static/icons/clock.svg" class="icon-image-small" mode="aspectFit"></image>
              <text class="info-text">上次签到：{{ person.lastSignTime }}</text>
            </view>
            <view class="info-row" v-if="person.overdueHours">
              <image src="/static/icons/alert-circle.svg" class="icon-image-small" mode="aspectFit"></image>
              <text class="info-text overdue">超时 {{ person.overdueHours }} 小时</text>
            </view>
          </view>
          
          <view class="item-actions">
            <view class="action-btn primary" @click.stop="callPerson(person)">
              <image src="/static/icons/phone.svg" class="icon-image-medium" mode="aspectFit"></image>
              <text>呼叫</text>
            </view>
            <view class="action-btn secondary" @click.stop="sendMessage(person)">
              <image src="/static/icons/message-circle.svg" class="icon-image-medium" mode="aspectFit"></image>
              <text>消息</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="filteredPersonnelList.length === 0" class="empty-state">
        <image src="/static/icons/users.svg" class="icon-image-large" mode="aspectFit"></image>
        <text class="empty-text">暂无待签人员</text>
      </view>
    </view>

    <!-- 批量操作按钮 -->
    <view class="batch-actions">
      <view class="batch-btn" @click="batchCall">
        <image src="/static/icons/phone.svg" class="icon-image-medium" mode="aspectFit"></image>
        <text>批量呼叫</text>
      </view>
      <view class="batch-btn" @click="batchMessage">
        <image src="/static/icons/message-circle.svg" class="icon-image-medium" mode="aspectFit"></image>
        <text>批量通知</text>
      </view>
    </view>

    <!-- 刷新按钮 -->
    <view class="refresh-btn" @click="refreshData">
      <image src="/static/icons/reload.svg" class="icon-image-medium" mode="aspectFit"></image>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 页面参数
const parkingLotId = ref('')
const parkingLotName = ref('')
const personnelList = ref([])
const activeFilter = ref('all')
const loading = ref(false)

// 页面加载
onLoad((options) => {
  parkingLotId.value = options.id || '1'
  parkingLotName.value = options.name || '停车场'
  loadData()
})

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 使用本地生成的模拟数据
    personnelList.value = generateMockPersonnel(20)
  } catch (error) {
    console.error('加载数据失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 生成模拟人员数据
const generateMockPersonnel = (count) => {
  const data = []
  const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']
  const positions = ['巡检员', '安保员', '管理员', '维护员']
  
  for (let i = 0; i < count; i++) {
    const lastSignDate = getRandomLastSignTime()
    const overdueHours = calculateOverdueHours(lastSignDate)
    
    const person = {
      id: `person_${Date.now()}_${i}`,
      name: names[Math.floor(Math.random() * names.length)] + (i + 3),
      position: positions[Math.floor(Math.random() * positions.length)],
      phone: `138****${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`,
      lastSignTime: lastSignDate,
      overdueHours: overdueHours > 0 ? overdueHours : null,
      isOverdue: overdueHours > 0,
      isTodayTarget: Math.random() > 0.3
    }
    data.push(person)
  }
  
  return data
}

// 获取随机上次签到时间
const getRandomLastSignTime = () => {
  const now = new Date()
  const randomHours = Math.floor(Math.random() * 72) // 0-72小时前
  const randomMinutes = Math.floor(Math.random() * 60)
  const date = new Date(now.getTime() - randomHours * 60 * 60 * 1000 - randomMinutes * 60 * 1000)
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hour}:${minute}`
}

// 计算超时小时数
const calculateOverdueHours = (lastSignTime) => {
  const now = new Date()
  const lastSign = new Date(lastSignTime)
  const diffMs = now.getTime() - lastSign.getTime()
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  
  // 假设24小时内需要签到，超过24小时算超时
  return diffHours > 24 ? diffHours - 24 : 0
}

// 筛选后的人员列表
const filteredPersonnelList = computed(() => {
  if (activeFilter.value === 'all') {
    return personnelList.value
  } else if (activeFilter.value === 'overdue') {
    return personnelList.value.filter(person => person.isOverdue)
  } else if (activeFilter.value === 'today') {
    return personnelList.value.filter(person => person.isTodayTarget)
  }
  return personnelList.value
})

// 获取超时人数
const getOverdueCount = () => {
  return personnelList.value.filter(person => person.isOverdue).length
}

// 获取今日应签人数
const getTodayCount = () => {
  return personnelList.value.filter(person => person.isTodayTarget).length
}

// 设置筛选器
const setFilter = (filter) => {
  activeFilter.value = filter
}

// 获取状态样式类
const getStatusClass = (person) => {
  if (person.isOverdue) return 'status-overdue'
  if (person.isTodayTarget) return 'status-target'
  return 'status-normal'
}

// 获取状态文本
const getStatusText = (person) => {
  if (person.isOverdue) return '超时'
  if (person.isTodayTarget) return '今日应签'
  return '正常'
}

// 查看人员详情
const viewPersonDetail = (person) => {
  const content = `姓名：${person.name}\n职位：${person.position}\n电话：${person.phone}\n上次签到：${person.lastSignTime}${person.overdueHours ? `\n超时：${person.overdueHours}小时` : ''}`
  
  uni.showModal({
    title: '人员详情',
    content: content,
    showCancel: false
  })
}

// 呼叫人员
const callPerson = (person) => {
  uni.showModal({
    title: '呼叫确认',
    content: `确定要呼叫 ${person.name} (${person.phone}) 吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '正在呼叫...',
          icon: 'success'
        })
      }
    }
  })
}

// 发送消息
const sendMessage = (person) => {
  uni.showModal({
    title: '发送消息',
    content: `确定要向 ${person.name} 发送签到提醒消息吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '消息已发送',
          icon: 'success'
        })
      }
    }
  })
}

// 批量呼叫
const batchCall = () => {
  const count = filteredPersonnelList.value.length
  uni.showModal({
    title: '批量呼叫',
    content: `确定要批量呼叫 ${count} 名人员吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '批量呼叫中...',
          icon: 'success'
        })
      }
    }
  })
}

// 批量通知
const batchMessage = () => {
  const count = filteredPersonnelList.value.length
  uni.showModal({
    title: '批量通知',
    content: `确定要向 ${count} 名人员发送签到提醒吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '批量通知已发送',
          icon: 'success'
        })
      }
    }
  })
}

// 刷新数据
const refreshData = () => {
  loadData()
  uni.showToast({
    title: '刷新成功',
    icon: 'success'
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.pending-sign-detail {
  min-height: 100vh;
  position: relative;
  padding-bottom: 120px;
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  backdrop-filter: blur(10px);
  padding-top: var(--status-bar-height);
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  padding: 0 16px;
}

.navbar-left,
.navbar-right {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  color: #fff;
}

.page-content {
  padding-top: calc(var(--status-bar-height) + 44px + 20px);
  padding-left: 16px;
  padding-right: 16px;
}

.stats-overview {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.stats-card {
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 16px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stats-number {
  font-size: 24px;
  font-weight: 700;
  color: #667eea;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 12px;
  color: #666;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-tabs {
  display: flex;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-tab {
  flex: 1;
  text-align: center;
  padding: 8px 12px;
  border-radius: 8px;
  font-size: 14px;
  color: #666;
  transition: all 0.3s ease;
  
  &.active {
    background: #667eea;
    color: #fff;
    font-weight: 600;
  }
}

.personnel-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.personnel-item {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
}

.item-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.person-avatar {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  background: #667eea;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.avatar-text {
  color: #fff;
  font-size: 16px;
  font-weight: 600;
}

.person-info {
  flex: 1;
}

.person-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 2px;
}

.person-position {
  font-size: 12px;
  color: #666;
}

.person-status {
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  
  &.status-overdue {
    background: #fee2e2;
    color: #dc2626;
  }
  
  &.status-target {
    background: #fef3c7;
    color: #d97706;
  }
  
  &.status-normal {
    background: #dcfce7;
    color: #16a34a;
  }
}

.item-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 6px;
}

.info-text {
  font-size: 14px;
  color: #666;
  
  &.overdue {
    color: #f56565;
    font-weight: 500;
  }
}

.item-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 8px 12px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  
  &.primary {
    background: #667eea;
    color: #fff;
    
    &:active {
      background: #5a67d8;
    }
  }
  
  &.secondary {
    background: rgba(102, 126, 234, 0.1);
    color: #667eea;
    
    &:active {
      background: rgba(102, 126, 234, 0.2);
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-text {
  margin-top: 16px;
  font-size: 16px;
  color: rgba(255, 255, 255, 0.7);
}

.batch-actions {
  position: fixed;
  bottom: 80px;
  left: 16px;
  right: 16px;
  display: flex;
  gap: 12px;
  z-index: 999;
}

.batch-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 12px;
  background: rgba(102, 126, 234, 0.9);
  color: #fff;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  backdrop-filter: blur(10px);
  
  &:active {
    transform: scale(0.95);
  }
}

.refresh-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  background: #667eea;
  border-radius: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  z-index: 999;
  
  &:active {
    transform: scale(0.95);
  }
}

/* 响应式适配 */
@media (max-width: 375px) {
  .stats-overview {
    gap: 8px;
  }
  
  .stats-card {
    padding: 12px;
  }
  
  .stats-number {
    font-size: 20px;
  }
  
  .page-content {
    padding-left: 12px;
    padding-right: 12px;
  }
  
  .batch-actions {
    left: 12px;
    right: 12px;
  }
}

/* 图标样式 */
.icon-image {
  width: 20px;
  height: 20px;
  filter: brightness(0) invert(1); /* 使SVG图标变为白色 */
}

.icon-image-small {
  width: 14px;
  height: 14px;
  filter: brightness(0) saturate(100%) invert(62%) sepia(8%) saturate(14%) hue-rotate(314deg) brightness(94%) contrast(92%); /* #999颜色 */
}

.icon-image-medium {
  width: 18px;
  height: 18px;
  filter: brightness(0) invert(1); /* 使SVG图标变为白色 */
}

.icon-image-large {
  width: 60px;
  height: 60px;
  filter: brightness(0) saturate(100%) invert(93%) sepia(0%) saturate(0%) hue-rotate(147deg) brightness(89%) contrast(96%); /* #ccc颜色 */
}

.info-row:has(.info-text.overdue) .icon-image-small {
  filter: brightness(0) saturate(100%) invert(42%) sepia(83%) saturate(1095%) hue-rotate(324deg) brightness(102%) contrast(96%); /* #f56565颜色 */
}

.action-btn.secondary .icon-image-medium {
  filter: brightness(0) saturate(100%) invert(50%) sepia(85%) saturate(2282%) hue-rotate(215deg) brightness(87%) contrast(90%); /* #667eea颜色 */
}
</style>